<template>
  <div class="monthly-report-container">
    <!-- 标题组件 -->
    <Title :title="title" :subtitle="subtitle"></Title>
    
    <!-- 图表容器 -->
    <div class="chart-wrapper">
      <div ref="pieChartContainer" style="height: 300px;"></div>
    </div>
    
    <!-- 数据说明 -->
    <div class="data-notes">
      <div class="note-item" v-for="item in legendData" :key="item.name">
        <span class="legend-color" :style="{backgroundColor: item.color}"></span>
        <span class="legend-text">{{ item.name }}: {{ item.value }}%</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Pie } from '@antv/g2plot';
import Title from './Title.vue';
import { ref, onMounted, onUnmounted } from 'vue';
import { get } from '@/utils/request';

// 组件标题和副标题
const title = ref('崇川区环境监测月报');
const subtitle = ref('2023年12月数据统计');

// 图表容器引用
const pieChartContainer = ref(null);
// 图表实例引用
let pieChart = null;
// 图例数据
const legendData = ref([]);

// 模拟崇川区环境监测数据（百分比）
const reportData = [
  { type: '空气质量监测', value: 35, color: '#5B8FF9' },
  { type: '水质监测', value: 28, color: '#5AD8A6' },
  { type: '噪声监测', value: 15, color: '#F6BD16' },
  { type: '土壤监测', value: 12, color: '#E86452' },
  { type: '辐射监测', value: 10, color: '#6DC8EC' },
];

// 更新图例数据
const updateLegendData = () => {
  legendData.value = reportData.map(item => ({
    name: item.type,
    value: item.value,
    color: item.color
  }));
};

// 加载饼图
const loadPieChart = () => {
  pieChart = new Pie(pieChartContainer.value, {
    data: reportData,
    angleField: 'value',
    colorField: 'type',
    color: ({ type }) => {
      const item = reportData.find(d => d.type === type);
      return item ? item.color : '#999';
    },
    radius: 0.8,
    innerRadius: 0.5,
    label: {
      type: 'spider',
      labelHeight: 28,
      content: '{name}\n{percentage}',
      style: {
        fill: '#fff',
        fontSize: 12,
        fontWeight: 'bold',
        textShadow: '0 1px 2px rgba(0,0,0,0.5)'
      },
    },
    legend: false, // 禁用内置图例，使用自定义图例
    tooltip: {
      domStyles: {
        'g2-tooltip': {
          background: 'rgba(0, 43, 77, 0.9)',
          color: '#fff',
          boxShadow: '0 4px 12px 0 rgba(0, 0, 0, 0.2)',
          borderRadius: '4px',
        },
        'g2-tooltip-list-item': {
          color: '#fff',
        },
      },
      customContent: (title, items) => {
        const currentItem = reportData.find(item => item.type === title);
        return `<div style="padding: 12px; min-width: 180px;">
          <div style="margin-bottom: 8px; color: ${currentItem.color}; font-weight: bold; font-size: 14px;">
            ${title}
          </div>
          <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
            <span>占比:</span>
            <span style="font-weight: bold;">${currentItem.value}%</span>
          </div>
          <div style="display: flex; justify-content: space-between;">
            <span>监测点位:</span>
            <span>${getMonitorSites(title)}</span>
          </div>
        </div>`;
      },
    },
    interactions: [
      { type: 'element-active' },
      { type: 'pie-statistic-active' },
    ],
    statistic: {
      title: {
        style: {
          color: '#fff',
          fontSize: '14px',
          fontWeight: 'bold',
        },
        content: '总监测比例',
      },
      content: {
        style: {
          color: '#fff',
          fontSize: '24px',
          fontWeight: 'bold',
          textShadow: '0 2px 4px rgba(0,0,0,0.5)',
        },
        content: '100%',
      },
    },
    animation: {
      appear: {
        animation: 'zoom-in',
        duration: 2000,
      },
      update: {
        animation: 'path-in',
        duration: 1000,
      },
    },
  });

  pieChart.render();
  updateLegendData();
};

// 获取各类监测对应的点位数量
const getMonitorSites = (type) => {
  const sitesMap = {
    '空气质量监测': '32个',
    '水质监测': '18个',
    '噪声监测': '25个',
    '土壤监测': '8个',
    '辐射监测': '5个'
  };
  return sitesMap[type] || '--';
};

// 获取真实数据
const fetchReportData = async () => {
  try {
    const res = await get('/api/nantong/chongchuan/monthly-report');
    console.log('监测月报数据:', res);
    // 处理返回数据并更新图表
    // pieChart.changeData(res.data);
  } catch (error) {
    console.error('获取监测月报数据失败:', error);
  }
};

onMounted(async () => {
  await fetchReportData();
  loadPieChart();
});

onUnmounted(() => {
  // 销毁图表实例
  if (pieChart) {
    pieChart.destroy();
  }
});
</script>

<style lang="less" scoped>
.monthly-report-container {
  background: rgba(16, 42, 67, 0.5);
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  .chart-wrapper {
    margin: 0 auto;
    width: 100%;
    max-width: 500px;
  }

  .data-notes {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 12px;
    margin-top: 16px;

    .note-item {
      display: flex;
      align-items: center;
      padding: 4px 8px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 4px;

      .legend-color {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 2px;
        margin-right: 6px;
      }

      .legend-text {
        color: #fff;
        font-size: 12px;
      }
    }
  }

  // 响应式调整
  @media (max-width: 768px) {
    padding: 12px;

    .data-notes {
      gap: 8px;
      
      .note-item {
        padding: 2px 6px;
      }
    }
  }
}
</style>